/**
 * Copyright (c) 2012, lincomb Technology CO,LDT. All rights reserved.
 * Module: App推送
 * File: NotificationAction.java
 * Purpose: 处理App推送Action层
 * Date: 2016-6-6
 */
package com.edais.actions;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.edais.domain.AfficheTab;
import com.edais.domain.PushMessageRecord;
import com.edais.domain.UnReadMsgInfo;
import com.edais.service.PushMessageService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.Message;
import com.edais.util.StringUtil;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;

/**
 * ClassName: NotificationAction 
 * @Description: 处理App推送消息Action类
 * @author ZuoJun
 * @date 2016-6-6 16:15:29
 */
@Controller
@RequestMapping("/push")

public class NotificationAction implements Serializable{

	private static final Log logger = LogFactory.getLog(NotificationAction.class);
	
	@Autowired
	private PushMessageService pushMessageService;
	
	/**
	 * @Description: 根据用户ID、消息类别查询消息或公告信息
	 * @param request
	 * @param response
	 * @author gongyanlan
	 * @date 2017-2-16 
	 */
	@RequestMapping(value = "/queryMessage")
	public void queryMessage(HttpServletRequest request, HttpServletResponse response){
			logger.info("/push/queryMessage NotificationAction queryMessage() start ");
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);
			logger.info("header：" + header.toString());
			Map<String,Object> params=null;
			try {
				params = RequestUtil.decodeData(request);	// 解密请求参数
			} catch (Exception e) {
				logger.error(" 解密请求参数失败：" ,e);
				ResultDTO<PushMessageRecord>  resultDTO = new ResultDTO<PushMessageRecord>(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				String result  = resultDTO.toJsonString();
				ResponseUtil.write(response,  result);
				return;
			}
			logger.info("data：" + params.toString());
			//用户ID
			String userId = String.valueOf(header.getUserId()); 
			//消息类别(0.消息，1.公告)(服务端设置默认值0)
			String type = String.valueOf(params.get("type"));
			//当前页数
			String currentStr = String.valueOf(params.get("current"));		
			//页面大小
			String pageSizeStr = String.valueOf(params.get("pageSize"));
			logger.info("/push/queryMessage NotificationAction queryMessage() userId=" + userId + " , type=" + type + " ,  current=" + currentStr + " , pageSize=" + pageSizeStr);
			if(StringUtil.isEmpty(userId)){
					logger.info("/push/queryMessage NotificationAction unread() userId=" + userId + " , userId为空!");
					ResultDTO<PushMessageRecord>  resultDTO = new ResultDTO<PushMessageRecord> (ResultCode.FAILED,"用户id不能为空！");
					String result  = resultDTO.toJsonString();
					ResponseUtil.write(response,  result);
				return;
			}
			if(StringUtil.isEmpty(type)){
				//设置默认值为0
				type = "0";
				logger.info("/push/queryMessage NotificationAction queryMessage() type=" + type + " , type为空!");
			}
			if(StringUtil.isEmpty(currentStr)){
				//设置默认值为1
				currentStr = "1";
				logger.info("/push/queryMessage NotificationAction queryMessage() current=" + currentStr + " , current为空!");
			}
			if(StringUtil.isEmpty(pageSizeStr)){
				//设置默认值为10
				pageSizeStr = "10";
				logger.info("/push/queryMessage NotificationAction queryMessage() pageSize=" + pageSizeStr + " , pageSize为空!");
			}
			if("0".equals(type)){
				type = "20";//消息类别(20.个人消息，2.媒体报道，3.最新活动，21.平台公告，5.咨询，6.客服信息) 
			}else if("1".equals(type)){
				type = "21";
			}
			int current = Integer.parseInt(currentStr);
			int pageSize = Integer.parseInt(pageSizeStr);
			//重新组装参数	
			params.put("userId", userId);
			params.put("messageType", type);
			params.put("rowBegin", (current - 1) * pageSize + 1);
			params.put("rowEnd", current * pageSize);
			params.put("current", current);
			params.put("pageSize", pageSize);
			ResultDTO<PushMessageRecord> rstDTO = null;
			rstDTO = pushMessageService.queryMessage(params);
			String result  = rstDTO.toJsonString();
			ResponseUtil.write(response,  result);
			logger.info(" /push/queryMessage NotificationAction queryMessage() end");
	}
	
	
	/**
	 * @Description: 查询媒体报道信息
	 * @param request
	 * @param response
	 * @author gongyanlan
	 * @date 2017-2-16 
	 */
	@RequestMapping(value = "/queryMediaReport")
	public void queryMediaReport(HttpServletRequest request, HttpServletResponse response){
			logger.info("/push/queryMediaReport NotificationAction queryMediaReport() start ");
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);
			logger.info("header：" + header.toString());
			Map<String,Object> params=null;
			try {
				params = RequestUtil.decodeData(request);	// 解密请求参数
			} catch (Exception e) {
				logger.error(" 解密请求参数失败：" ,e);
				ResultDTO<PushMessageRecord>  resultDTO = new ResultDTO<PushMessageRecord>(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				String result  = resultDTO.toJsonString();
				ResponseUtil.write(response,  result);
				return;
			}
			logger.info("data：" + params.toString());
			//当前页数
			String currentStr = String.valueOf(params.get("current"));		
			//页面大小
			String pageSizeStr = String.valueOf(params.get("pageSize"));
			//消息类别
			String sign=(String)params.get("sign");
			logger.info("/push/queryMediaReport NotificationAction queryMediaReport() current=" + currentStr + " , pageSize=" + pageSizeStr+ " , sign=" + sign );
			if(StringUtil.isEmpty(currentStr)){
				//设置默认值为1
				currentStr = "1";
				logger.info("/push/queryMessage NotificationAction queryMediaReport() current=" + currentStr + " , current为空!");
			}
			if(StringUtil.isEmpty(pageSizeStr)){
				//设置默认值为10
				pageSizeStr = "10";
				logger.info("/push/queryMessage NotificationAction queryMediaReport() pageSize=" + pageSizeStr + " , pageSize为空!");
			}
			int current = Integer.parseInt(currentStr);
			int pageSize = Integer.parseInt(pageSizeStr);
			//重新组装参数	
			params.put("sign",sign);//(ANNOUNCEMENT:公告;NEWS:新闻;PHONE：手机端 ACTIVITY:活动 CONSULTATION:资讯)
			params.put("rowBegin", (current - 1) * pageSize + 1);
			params.put("rowEnd", current * pageSize);
			params.put("current", current);
			params.put("pageSize", pageSize);
			ResultDTO<AfficheTab> rstDTO = pushMessageService.queryMediaReport(params);
			String result  = rstDTO.toJsonString();
			ResponseUtil.write(response,  result);
			logger.info(" /push/queryMediaReport NotificationAction queryMediaReport() end");
	}
	
	/**
	 * @Description: 查询未读信息数量
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/unread")
	public void unread(HttpServletRequest request, HttpServletResponse response){
			if (!RequestUtil.validSign(request)) {
				logger.info("无效签名");
				ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
				return;
			}
			if (!RequestUtil.validToken(request)) {
				logger.info("无效token");
				ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
				return;
			}
			RequestHeader header = RequestUtil.decodeHeader(request);
			logger.info("header：" + header.toString());
			//用户ID
			String userId = String.valueOf(header.getUserId()); 
			if(StringUtil.isEmpty(userId)){
					logger.info("/push/unread NotificationAction unread() userId=" + userId + " , userId为空!");
					ResultDTO<Map<String, Object>> resultDTO = new ResultDTO<Map<String, Object>>(ResultCode.FAILED,"用户id不能为空！");
					String result  = resultDTO.toJsonString();
					ResponseUtil.write(response,  result);
				return;
			}
			userId=userId.trim();
			int totalMsgNum=0;
			Map<String,Object> params=new HashMap<String,Object>();
			params.put("userId", userId);
			 List<UnReadMsgInfo> resultList=pushMessageService.queryUnReadNumList(params);//查询未读信息数量
			if(resultList!=null){
				for(UnReadMsgInfo unReadMsgInfo:resultList){
					int messageCount=0;
					if(unReadMsgInfo!=null){
						messageCount=unReadMsgInfo.getMessageCount();
						if(messageCount!=0){
							totalMsgNum+=messageCount;
						}
						if(unReadMsgInfo.getWebview()==null){
							unReadMsgInfo.setWebview("");
						}
					}
					
				}
			}
			ResultDTO<Map<String, Object>> resultDTO = new ResultDTO<Map<String, Object>>(ResultCode.SUCCESS);
			JSONObject jsonObj=resultDTO.toJson();
			jsonObj.put("list", resultList);
			jsonObj.put("totalMsgNum", totalMsgNum);
			ResponseUtil.write(response, jsonObj.toJSONString());
	}
	

	/**
	 * @Description: 清除未读消息数
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/clearUnread")
	public void clearUnread(HttpServletRequest request, HttpServletResponse response){
				
		logger.info("---------------------------- /push/clearUnread NotificationAction clearUnread() start ----------------------------");
				
		// 解密请求参数
		Map<String, Object> params = CommonUtil.getDecryptParameter(request);
		//用户ID
		String userId = (String)params.get("userId"); 
		String message_type=(String)params.get("message_type");	
		if(StringUtil.isEmpty(userId)){
			String result = CommonUtil.setResultStringCn( 
					new HashMap<String, Object>(),Consts.CHECK_CODE,"userId.is.null","用户id不能为空！");
				CommonUtil.responseJson(result, response);
				logger.info("---------------------------- /push/clearUnread NotificationAction clearUnread() userId=" 
				+ userId + " , userId为空! ----------------------------");
			return;
		}
		
		if(StringUtil.isEmpty(message_type)){
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.CHECK_CODE, 
					"message_type.is.null","消息类型不能为空！");
				CommonUtil.responseJson(result, response);
				logger.info("---------------------------- /push/clearUnread NotificationAction clearUnread() message_type=" 
				+ message_type + " , message_type为空! ----------------------------");
			return;
		}
		userId=userId.trim();
		message_type=message_type.trim();
		try {
			//暂时推送消息类型 只有 0:所有类型，3：最新活动，20：个人消息，21：平台公告,2:媒体报道,5:咨询
			if(message_type.equals("0")||message_type.equals("3")||message_type.equals("20")||message_type.equals("21")||message_type.equals("2")||message_type.equals("5")){
				pushMessageService.clearUnReadNum(params) ;//清除未读消息数
			}else{
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(),Consts.CHECK_CODE, 
						"message_type","消息类型暂不支持！");
					CommonUtil.responseJson(result, response);
					logger.info("---------------------------- /push/clearUnread NotificationAction clearUnread() message_type=" 
					+ message_type + " , message_type为空! ----------------------------");
				return;
			}
		} catch (Exception e) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, 
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
			logger.info("---------------------------- /push/clearUnread NotificationAction clearUnread() 出现异常 " 
				+ CommonUtil.printStackTraceToString(e) + " ----------------------------");
			e.printStackTrace();
			return;
		}
		String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.SUCCESS_CODE,Consts.SUCCESS_DESCRIBE, "");
		CommonUtil.responseJson(result, response);
		
	}
	
	/**
	 * @Description: 查询媒体报道详细信息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryMediaReportDetail")
	public void queryMediaReportDetail(HttpServletRequest request, HttpServletResponse response){
		System.out.println("==================sdfsdfsdfsdfs");		
		//解密请求参数
		Map<String, Object> params = CommonUtil.getDecryptParameter(request);
		//用户ID
		String id =(String)params.get("id"); 
		if(StringUtil.isEmpty(id)){
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.CHECK_CODE,"id.is.null","id不能为空！");
				CommonUtil.responseJson(result, response);
				logger.info("---------------------------- /push/unread NotificationAction queryMediaReportDetail() id=" 
				+ id + " , id为空! ----------------------------");
			return;
		}
		id=id.trim();
		Map<String, Object> rtnMap=new HashMap<String, Object>();
		Map<String, Object> resultDetail=null;
		try {
			resultDetail=pushMessageService.queryMediaReportDetail(params);
			if(resultDetail!=null){
				String content=resultDetail.get("content")+"";
				if(StringUtil.isNotEmpty(content)){
					resultDetail.put("content", replayAStr(content));//string2Json(content)) ;
				}
			}
			rtnMap.put("result", resultDetail);
		} catch (Exception e) {
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, 
					Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
			logger.info("---------------------------- /push/queryMediaReportDetail NotificationAction queryMediaReportDetail() 出现异常 " 
				+ CommonUtil.printStackTraceToString(e) + " ----------------------------");
			return;
		}
		String result = CommonUtil.setResultStringCn(
				rtnMap, Consts.SUCCESS_CODE,Consts.SUCCESS_DESCRIBE, "");
		CommonUtil.responseJson(result, response);
	}
	
	public String replayAStr(String s){
		if(null!=s){
			s=s.replaceAll("</?(a)\\s*?.*?>"," ");
		}
		return s;
	}
	
	public String string2Json(String s){
		StringBuffer sb = new StringBuffer();        
        for (int i=0; i<s.length(); i++) {  
            char c = s.charAt(i);    
             switch (c){  
             case '\"':        
                 sb.append("\\\"");        
                 break;        
             case '\\':        
                 sb.append("\\\\");        
                 break;        
             case '/':        
                 sb.append("\\/");        
                 break;        
             case '\b':        
                 sb.append("\\b");        
                 break;        
             case '\f':        
                 sb.append("\\f");        
                 break;        
             case '\n':        
                 sb.append("\\n");        
                 break;        
             case '\r':        
                 sb.append("\\r");        
                 break;        
             case '\t':        
                 sb.append("\\t");        
                 break;        
             default:        
                 sb.append(c);     
             }  
         }  
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++："+sb.toString());
        return sb.toString();     
	}
}
